<?php
namespace app\index\controller;
use app\index\model\Seek as SeekModel;
use think\Controller;
use app\index\model\Goods as GoodsModel;
use app\index\model\Life as LifeModel;

//首页
class Index extends Controller
{
    public function __construct()
    {
        header("Access-Control-Allow-Origin: *");//允许跨域
        header('Content-type: application/json');
        header("Access-Control-Allow-Methods:POST");
        header("access-control-allow-headers: Origin, X-Requested-With, Content-Type, Accept,WG-App-Version, WG-Device-Id, WG-Network-Type, WG-Vendor, WG-OS-Type, WG-OS-Version, WG-Device-Model, WG-CPU, WG-Sid, WG-App-Id, WG-Token,authorization");
    }

    /**
     * 轮播图
     */
    public function chartLst()
    {
        $list = db('chart',[],false)->where('ct_status',1)->field('ct_status,ct_create_time',true)->select();

        $info['code']    = '200';
        $info['data']    = $list;
        echo displayJson($info);die;
    }

    /**
     * 每个分类展示4个商品
     */
    public function index()
    {
        $count      = 4; //每个分类展示条数

        $cat_list   = db('classify',[],false)->where('cf_status',1)->order('cf_id asc')->select();

        $newArr = array();
        $field  = array('gd_id','gd_title','gd_money','gd_talk_price','gd_image_1','gd_desc','gd_click','gd_school','gd_create_time','gd_re_status');
        $field_goods = array('gd_id','gd_title','gd_image_1','gd_create_time');

        foreach ($cat_list as $val) {
            $newArr[$val['cf_en_name']] = db('goods',[],false)
                ->where('gd_status',1)
                ->where('gd_goods_status',1)
                ->where('gd_classify',$val['cf_id'])
                ->field($field)
                ->order('gd_click DESC,gd_create_time')
                ->limit($count)
                ->select();
        }

        $default_arr = array(
            'default_image' => 'http://www.taoerhuo.top/bishe/public/image/index/default_goods.jpg'
        );

        //添加好货推荐
        $recommend_list = db('goods',[],false)
            ->where('gd_status',1)
            ->where('gd_goods_status',1)
            ->where('gd_re_status',2)
            ->field($field_goods)
            ->order('gd_click  DESC,gd_create_time')
            ->select();

        $newArr['recommend_goods'] = $recommend_list;

        foreach ($newArr as $key => &$val) {
            foreach ($val as $k => &$v) {
                $v['gd_create_time'] = date('Y-m-d',$v['gd_create_time']);
            }
            if ($key != 'recommend_goods') {
                if (count($val) < $count) {
                    //分类下数据不够4条
                    $num = $count - count($val);

                    for ($i = 0; $i < $num; $i++) {
                         array_push($val,$default_arr);
                    }
                }
            }
        }

        $info['code']    = '200';
        $info['data']    = $newArr;
        echo displayJson($info);die;

    }

    /**
     * 商品筛选页
     */
    public function allGoodsList()
    {
        $classify = input('classify');
        $school   = input('school');
        $order    = input('order',1); // 1:时间降序 2:时间升序 3:价格降序 4:价格升序 5:浏览量降序 6:浏览量升序
        $search_key = input('search_key'); //搜索内容

        $uid   = input('uid'); //登录用户id 如果有则返回其学校

        $where['gd_status']           = ['=',1];
        $where['gd_goods_status']     = ['=',1];

        $count       = 12; //每个页面展示条数

        if ($search_key) {
            $where['gd_title|gd_desc|gd_school'] = ['like',"%".$search_key."%"];
        }

        if ($classify) {
            if ($classify == '999') {
                //好货推荐
                $where['gd_re_status'] = ['=',2];
            } else {
                $where['gd_classify'] = ['=',$classify];
            }
        }

        if ($school) {
            $where['gd_school'] = ['=',$school];
        }

        $field  = array('gd_id','gd_title','gd_money','gd_talk_price','gd_image_1','gd_desc','gd_click','gd_school','gd_create_time');

        switch ($order) {
            case 1:
                $sort = 'gd_create_time desc';
                break;
            case 2:
                $sort = 'gd_create_time asc';
                break;
            case 3:
                $sort = 'gd_money desc';
                break;
            case 4:
                $sort = 'gd_money asc';
                break;
            case 5:
                $sort = 'gd_click desc';
                break;
            case 6:
                $sort = 'gd_click asc';
                break;
            default:
                $info['code']    = '400';
                $info['message'] = '排序类型选择错误';
                echo displayJson($info);die;
        }

        $list = GoodsModel::where($where)->field($field)->order($sort)->paginate($count);

        $data = displayJson($list);

        $arr  = json_decode($data,true);

        $newArr = $arr['data'];

        $total    = $arr['total']; //总条数
        $per_page = $arr['per_page']; //每页显示条数

        $total_page = ceil($total/$per_page); //总页数

        $arr['total_page'] = $total_page;

        foreach ($newArr as $key => $val) {
            $newArr[$key]['gd_create_time'] = date('Y-m-d',$val['gd_create_time']);
        }

        $arr['school']  = '';
        if ($uid) {
            $us_school      = db('user',[],false)->where('us_id',$uid)->value('us_school');
            $arr['school']  = $us_school;
        }

        $arr['data'] = $newArr;

        $arr['transfer_school'] = $school;

        $info['code']    = '200';
        $info['message'] = '获取成功';
        $info['data']    = $arr;
        echo displayJson($info);die;
    }

    /**
     * 求购信息列表
     */
    public function seekLst()
    {
        $search_key = input('search_key'); //搜索内容

        $where['sk_status']        = ['=',1];
        $where['sk_condition']     = ['=',1];
        $where['sk_title|sk_desc|sk_school'] = ['like',"%".$search_key."%"];

        $list = SeekModel::where($where)
            ->field('sk_condition,sk_status,sk_del_aid,sk_note,sk_del_time',true)
            ->order('sk_create_time DESC')
            ->paginate(10);

        $data = displayJson($list);

        $arr  = json_decode($data,true);

        $newArr = $arr['data'];

        $total    = $arr['total']; //总条数
        $per_page = $arr['per_page']; //每页显示条数

        $total_page = ceil($total/$per_page); //总页数

        $arr['total_page'] = $total_page;

        $userIds    = array(); //用户id数组
        foreach ($newArr as $key => $val) {
            $userIds[] = $val['sk_uid'];
        }

        $user_list = $this->getUserEmailByIds($userIds);

        foreach ($newArr as $key => &$val) {
            $val['us_image'] = $user_list[$val['sk_uid']]['us_image'];
            $val['us_sex']   = $user_list[$val['sk_uid']]['us_sex'];

            if ($user_list[$val['sk_uid']]['us_phone_status'] == 2) {
                $val['us_phone'] = plum_format_mobile($user_list[$val['sk_uid']]['us_phone']);
            } else {
                $val['us_phone'] = $user_list[$val['sk_uid']]['us_phone'];
            }

            $val['us_qq']    = $user_list[$val['sk_uid']]['us_qq'];
            $val['us_wx']    = $user_list[$val['sk_uid']]['us_wx'];
            $val['us_email'] = $user_list[$val['sk_uid']]['us_email'];

            if (!$user_list[$val['sk_uid']]['us_username']) {
                $val['us_nickname']   = $user_list[$val['sk_uid']]['us_email'];
            } else {
                $val['us_nickname']   = $user_list[$val['sk_uid']]['us_username'];
            }

            $val['sk_create_time'] = date('Y-m-d',$val['sk_create_time']);
        }

        $arr['data'] = $newArr;

        $info['code'] = '200';
        $info['data'] = $arr;

        echo displayJson($info);die;
    }

    /**
     * 动态信息列表
     */
    public function lifeList()
    {
        $search_key = input('search_key'); //搜索内容

        $where['sl_content'] = ['like',"%".$search_key."%"];
        $where['sl_status']  = ['=',1];

        $list = LifeModel::where($where)
            ->order('sl_create_time desc,sl_click_num desc')
            ->paginate(10);

        $data = displayJson($list);

        $arr  = json_decode($data,true);

        $newArr = $arr['data'];

        $total    = $arr['total']; //总条数
        $per_page = $arr['per_page']; //每页显示条数

        $total_page = ceil($total/$per_page); //总页数

        $arr['total_page'] = $total_page;

        $userIds    = array(); //用户id数组
        foreach ($newArr as $key => $val) {
            $userIds[] = $val['sl_uid'];
        }

        $user_list = $this->getUserEmailByIds($userIds);

        foreach ($newArr as $key => &$val) {
            $val['us_image'] = $user_list[$val['sl_uid']]['us_image'];
            $val['us_sex']   = $user_list[$val['sl_uid']]['us_sex'];

            if ($user_list[$val['sl_uid']]['us_phone_status'] == 2) {
                $val['us_phone'] = plum_format_mobile($user_list[$val['sl_uid']]['us_phone']);
            } else {
                $val['us_phone'] = $user_list[$val['sl_uid']]['us_phone'];
            }

            $con =  strip_tags($val['sl_content']);
            if(mb_strlen($con) >500){
                $val['sl_content']  = mb_substr($con,0,500,'UTF-8') .'...';
            }

            $val['us_school']= $user_list[$val['sl_uid']]['us_school'];
            $val['us_qq']    = $user_list[$val['sl_uid']]['us_qq'];
            $val['us_wx']    = $user_list[$val['sl_uid']]['us_wx'];
            $val['us_email'] = $user_list[$val['sl_uid']]['us_email'];

            if (!$user_list[$val['sl_uid']]['us_username']) {
                $val['us_nickname']   = $user_list[$val['sl_uid']]['us_email'];
            } else {
                $val['us_nickname']   = $user_list[$val['sl_uid']]['us_username'];
            }

            $val['sl_create_time'] = date('Y-m-d',$val['sl_create_time']);
        }

        $arr['data'] = $newArr;

        $info['code'] = '200';
        $info['data'] = $arr;

        echo displayJson($info);die;
    }

    /**
    * 获取校园生活详情--游客查看
    */
    public function getLifeDesc()
    {
        $sl_id = input('sl_id');

        if (empty($sl_id)) {
            $info['code']     = '400';
            $info['message']  = '数据异常';
            echo displayJson($info);die;
        }

        $get = db('school_life',[],false)->where('sl_id',$sl_id)->find();

        if ($get) {
            //点击量自增1
            db('school_life',[],false)->where('sl_id',$sl_id)->setInc('sl_click_num');

            $info['code']     = '200';
            $info['data']     = $get;
            echo displayJson($info);die;
        } else {
            $info['code']     = '400';
            $info['message']  = '数据获取失败，请刷新重试';
            echo displayJson($info);die;
        }
    }

    /**
     * 举报动态
     */
    public function reportLife()
    {
        $id  = input('sl_id'); //动态id

        if (!$id) {
            $info['code']     = '400';
            $info['message']  = '参数丢失';
            echo displayJson($info);die;
        }

        $life = db('school_life',[],false)->where('sl_id',$id)->find();

        if (!$life) {
            $info['code']     = '400';
            $info['message']  = '未找到该动态';
            echo displayJson($info);die;
        }

        $res = db('school_life',[],false)->where('sl_id',$id)->setInc('sl_report_num');

        if ($res) {
            $info['code']     = '200';
            $info['message']  = '举报成功，我们会及时处理';
            echo displayJson($info);die;
        } else {
            $info['code']     = '400';
            $info['message']  = '服务器繁忙，请稍后重试';
            echo displayJson($info);die;
        }
    }

    /**
     * 商品详情 同时获取留言列表
     */
    public function getGoodsDesc()
    {
        $id  = input('gd_id'); //商品id
        $uid = input('us_id'); //用户id

        $rowGoods = db('goods',[],false)
            ->where('gd_id',$id)
            ->where('gd_status',1)
            ->field('gd_report_note,gd_report_num,gd_del_time,gd_del_note,gd_del_aid,gd_status,gd_goods_status,',true)
            ->find();

        $user_row = db('user',[],false)->where('us_id',$rowGoods['gd_uid'])->find();

        if ($rowGoods) {

            //商品点击量加一
            db('goods',[],false)->where('gd_id',$id)->setInc('gd_click');

            if (isset($uid) && !empty($uid)) {
                $user_info = db('user',[],false)->where('us_id',$uid)->find();

                if ($user_info['us_status'] == 2) {
                    $info['code']     = '401';
                    $info['message']  = '您的状态异常，将自动退出登录。如有疑问，请联系管理员';
                    echo displayJson($info);die;
                }

                //获取该商品是否已被当前用户收藏
                $checkCollect = db('collect',[],false)->where('cc_uid',$uid)->where('cc_gid',$id)->find();

                if ($checkCollect) {
                    //已被收藏
                    $rowGoods['collect_status'] = 1;
                } else {
                    //未被收藏
                    $rowGoods['collect_status'] = 0;
                }

                //判断是否是查看自己的商品
                if ($rowGoods['gd_uid'] == $uid) {
                    $rowGoods['my_goods'] = 1;
                } else {
                    $rowGoods['my_goods'] = 0;
                }
            } else {
                $rowGoods['collect_status'] = 0;
                $rowGoods['my_goods'] = 0;
            }

            $rowGoods['gd_classify']    = db('classify',[],false)->where('cf_id',$rowGoods['gd_classify'])->value('cf_name');
            $rowGoods['gd_create_time'] = date('Y-m-d',$rowGoods['gd_create_time']);
            $rowGoods['user_sign']      = $user_row['us_desc']; //个性签名
            $rowGoods['user_sex']       = $user_row['us_sex']; //性别
            $rowGoods['user_username']  = $user_row['us_username']; //昵称
            $rowGoods['user_image']     = $user_row['us_image']; //头像
            $rowGoods['user_qq']        = $user_row['us_qq'];
            $rowGoods['user_wx']        = $user_row['us_wx'];
            if ($user_row['us_phone_status'] == 2) {
                $rowGoods['user_phone']     = plum_format_mobile($user_row['us_phone']);
            } else {
                $rowGoods['user_phone']     = $user_row['us_phone'];
            }
            $rowGoods['user_email']     = $user_row['us_email'];

            //获取留言
            $getLiu  = db('liuyan',[],false)->where('ly_gid',$id)->where('ly_status',1)->order('ly_id desc')->select();

            $num     = count($getLiu);

            $newLiuYanList = array();
            if ($getLiu) {
                foreach ($getLiu as $key => $val) {
                    $newLiuYanList[$key]['liu_id']      = $val['ly_id'];
                    $newLiuYanList[$key]['liu_uname']   = $val['ly_uname'];
                    $newLiuYanList[$key]['liu_uimage']  = $val['ly_uimage'];
                    $newLiuYanList[$key]['liu_content'] = $val['ly_content'];
                    $newLiuYanList[$key]['liu_time']    = date('Y-m-d H:i',$val['ly_create_time']);
                    $newLiuYanList[$key]['liu_del']     = (int)$val['ly_uid'] == (int)$uid ? '2' : '1'; //1：不能删除 2：属于自己的留言 可以删除
                    $newLiuYanList[$key]['liu_number']  = ($num - $key).'楼'; //留言排序 楼层
                }
            }

            $rowGoods['ly_list'] = $newLiuYanList;

            $info['code']     = '200';
            $info['data']     = $rowGoods;
            echo displayJson($info);die;
        } else {
            $info['code']     = '400';
            $info['message']  = '未找到该商品或商品已经下架';
            echo displayJson($info);die;
        }

    }

    /**
     * 举报商品
     */
    public function reportGoods()
    {
        $gid  = input('gid'); //商品id
        $note = input('note'); //举报原因

        if (!$gid) {
            $info['code']     = '400';
            $info['message']  = '参数丢失';
            echo displayJson($info);die;
        }

        if (!$note) {
            $info['code']     = '400';
            $info['message']  = '请选择举报原因';
            echo displayJson($info);die;
        }

        $goods = db('goods',[],false)->where('gd_id',$gid)->where('gd_status',1)->find();

        if (!$goods) {
            $info['code']     = '400';
            $info['message']  = '未找到该商品或商品已经下架';
            echo displayJson($info);die;
        }

        //举报原因，以；分隔
        $report_note = $goods['gd_report_note'];

        $report_arr  = explode('；',$report_note);

        if (!in_array($note,$report_arr)) {
            if (empty($report_arr)) {
                $set['gd_report_note'] = $note.'；';
            } else {
                $set['gd_report_note'] = $goods['gd_report_note'].$note.'；';
            }
        }
        $set['gd_report_num'] = $goods['gd_report_num'] + 1; //被举报次数

        $res = db('goods',[],false)->where('gd_id',$gid)->update($set);

        if ($res) {
            $info['code']     = '200';
            $info['message']  = '举报成功，我们会及时处理';
            echo displayJson($info);die;
        } else {
            $info['code']     = '400';
            $info['message']  = '服务器繁忙，请稍后重试';
            echo displayJson($info);die;
        }
    }



    /*
     * 根据id数组 获取用户邮箱 显示状态 以us_id为key
     * @param array $ids
     */
    public function getUserEmailByIds($ids)
    {
        $newArr = array();
        if (!empty($ids)) {
            $res = db('user',[],false)->where('us_id','in',$ids)
                ->field('us_id,us_email,us_username,us_sex,us_school,us_qq,us_wx,us_phone,us_phone_status,us_image')
                ->select();

            foreach ($res as $val) {
                $newArr[$val['us_id']] = $val;
            }
        }

        return $newArr;
    }

}